import 'dart:math';

class HomeUtil {
  List<List<double>> originalData = [];
  int minutes = 100;
  int second = 2;
  List<double> ignore = [0];
  double maxValue = 0;
  double minValue = 0;
  double averageValue = 0;
  List<double> validData = [];
  double get gap => maxValue - minValue;
  HomeUtil(this.second) {
    _init();
  }

  void _init() {
    originalData = List.generate(minutes, (_) => List.generate(60 ~/ second, (_) => 0));
    validData = List.generate(minutes, (_) => 0.0);
  }

  int sec = 0;
  void update(double v) {
    if (sec >= 60) {
      sec = 0;
      originalData.removeAt(0);
      originalData.add(List.generate(60 ~/ second, (_) => 0));
    } else {
      originalData.last.add(v);
      originalData.last.removeAt(0);
    }

    sec += second;
    _computeAverages();
  }

  void _computeAverages() {
    for (var i = 0; i < originalData.length; i++) {
      List<double> subList = originalData[i];
      double temp_max = subList.reduce(max).ceilToDouble();
      double temp_min = subList.reduce(min).floorToDouble();
      maxValue = max(temp_max, maxValue);
      minValue = min(temp_min, minValue);
      // 获取符合条件的有效值
      List<double> validList = subList.where((value) => !ignore.contains(value)).toList();
      if (validList.isNotEmpty) {
        double avg = validList.reduce((a, b) => a + b) / validList.length; // 计算平均值
        validData[i] = avg;
      } else {
        validData[i] = 0;
      }
    }
  }
}
